<?php

set_time_limit( 0 );

$curl = curl_init();
$ini_options = array(
    CURLOPT_AUTOREFERER => true,
    CURLOPT_BINARYTRANSFER => true,
    //   CURLOPT_CERTINFO=>false,
    CURLOPT_COOKIESESSION => false,
    CURLOPT_DNS_USE_GLOBAL_CACHE => false,
    CURLOPT_FAILONERROR => false,
    CURLOPT_FILETIME => false,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_FORBID_REUSE => false,
    CURLOPT_FRESH_CONNECT => false,
    CURLOPT_HEADER => false,
    CURLINFO_HEADER_OUT => false,
    CURLOPT_HTTPGET => true,
    CURLOPT_NOPROGRESS => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_VERBOSE => true,
    //CURLOPT_HTTP_VERSION=>CURLOPT_HTTP_VERSION_1_1,
    CURLOPT_PORT => 443,
    CURLOPT_SSL_VERIFYHOST => true,
    CURLOPT_SSLVERSION => 3,
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1',
    CURLOPT_COOKIEJAR => TEMP_PATH . 'cookie.txt', //OJO NO PUEDO USAR EL MISMO ARCHIVO PARA TODAS LAS CONEXIONES, etndría que ser una por empresa
    CURLOPT_COOKIEFILE => TEMP_PATH . 'cookie.txt'
);


//$options[CURLOPT_NOBODY]=true; no rula
//CURLOPT_HTTPGET
//CURLOPT_POSTFIELDS //if is an array the content-type will send multipart/form-data
//CURLOPT_CUSTOMREQUEST='DELETE'
//CURLOPT_HTTPHEADER is an array with elements like 'Content-type: text/plain'


unlink( TEMP_PATH . 'cookie.txt' );

curl_setopt_array( $curl, $ini_options );


//ESTO ES PARA LOGUEAR A ALGUIEN DE GMAIL EN LA APLICACION, pero no me da autorizacion a nada, o para installed 

$data = array(
    //'scope'=>'https://docs.google.com/feeds/',
    'scope' => 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile',
    //'redirect_uri'=>'urn:ietf:wg:oauth:2.0:oob',
    'redirect_uri' => 'http://localhost/oauth.php',
    'response_type' => 'code',
    'client_id' => '76748848756.apps.googleusercontent.com'
);

$data_encoded = array( );
foreach ( $data as $k => $v )
        $data_encoded[ ] = urlencode( $k ) . '=' . urlencode( $v );
echo 'https://accounts.google.com/o/oauth2/auth?' . implode( '&', $data_encoded );

curl_setopt( $curl, CURLOPT_URL,
        'https://accounts.google.com/o/oauth2/auth?' . implode( '&',
                $data_encoded ) );

$contenido = curl_exec( $curl );
$pos_ini = strpos( $contenido, '<form' );
$pos_fin = strpos( $contenido, '</form>', $pos_ini );
$form_content = substr( $contenido, $pos_ini, $pos_fin - $pos_ini + 7 );

//eliminamos otras etiquetas excepto form e input
$form_content = strip_tags( $form_content, '<form><input>' );
$form_content = strrev( preg_replace( '/>\/?([^>]*tupni<)/', '>/ ${1}',
                strrev( $form_content ) ) );

$form = simplexml_load_string( strtr( $form_content, array( '&nbsp;' => '' ) ) );
unset( $contenido, $form_content );

$fields = array( );
foreach ( $form->input as $i )
        if ( $i[ 'name' ] != 'Email' && $i[ 'name' ] != 'Passwd' )
            $fields[ ] = urlencode( $i[ 'name' ] ) . '=' . urlencode( $i[ 'value' ] );

$fields[ ] = urlencode( 'Email' ) . '=' . urlencode( 'alejandro.gama@gmail.com' );
$fields[ ] = urlencode( 'Passwd' ) . '=' . urlencode( 'agc021078' );

unset( $contenido, $form_content );


curl_setopt( $curl, CURLOPT_URL, $form[ 'action' ] );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS, implode( '&', $fields ) );

$contenido = curl_exec( $curl );
$info = curl_getinfo( $curl );
$pos_ini = strpos( $contenido, '<form' );
$pos_fin = strpos( $contenido, '</form>', $pos_ini );
$form_content = substr( $contenido, $pos_ini, $pos_fin - $pos_ini + 7 );

//eliminamos otras etiquetas excepto form e input
$form_content = strip_tags( $form_content, '<form><input>' );
$form_content = strrev( preg_replace( '/>\/?([^>]*tupni<)/', '>/ ${1}',
                strrev( $form_content ) ) );

$form = simplexml_load_string( strtr( $form_content, array( '&nbsp;' => '' ) ) );
unset( $contenido, $form_content );


$fields = array( );
foreach ( $form->input as $i )
        if ( $i[ 'name' ] != 'deny' )
            $fields[ ] = urlencode( $i[ 'name' ] ) . '=' . urlencode( $i[ 'value' ] );

unset( $contenido, $form_content );

curl_setopt( $curl, CURLOPT_URL, $form[ 'action' ] );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS, implode( '&', $fields ) );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, false );
curl_setopt( $curl, CURLOPT_HEADER, true ); //obtengo la cabecera de respuesta

$contenido = curl_exec( $curl ); //DE aqui tengo que extraer el code;

$contenido = substr( $contenido, 0, strpos( $contenido, "\r\n\r\n" ) ); //solo queremos la cabecera
echo $contenido;
$coincidencias = array( );
preg_match( "/Location\s*:[^\?]*\?code=([^\r]*)/", $contenido, $coincidencias );
$code = urldecode( $coincidencias[ 1 ] );
unset( $contenido );


curl_setopt_array( $curl, $ini_options );
curl_setopt( $curl, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token' );
curl_setopt( $curl, CURLOPT_POST, true );


$data = array(
    'code' => $code,
    'redirect_uri' => 'http://localhost/oauth.php',
    'client_id' => '76748848756.apps.googleusercontent.com',
    'client_secret' => 'yfZGM3sxAA-SWbZ2dgREDRWQ',
    'grant_type' => 'authorization_code'
);

$fields = array( );
foreach ( $data as $k => $v )
        $fields[ ] = urlencode( $k ) . '=' . urlencode( $v );

curl_setopt( $curl, CURLOPT_POSTFIELDS, implode( '&', $fields ) );

$contenido = curl_exec( $curl );

//voy a simplificar esto para que sea más generalista
$coincidencias = array( );
preg_match_all( '/"([^"]*)"\s*:\s*([^,}]*)/', $contenido, $coincidencias );

$values = array( );
$num = count( $coincidencias[ 1 ] );
for ( $i = 0; $i < $num; $i++ ) {
    $coin = array( );

    if ( preg_match( '/"([^"]*)"/', $coincidencias[ 2 ][ $i ], $coin ) )
            $values[ $coincidencias[ 1 ][ $i ] ] = $coin[ 1 ];

    else if ( preg_match( '/(\d*)/', $coincidencias[ 2 ][ $i ], $coin ) )
            $values[ $coincidencias[ 1 ][ $i ] ] = ( int ) $coin[ 1 ];
}

curl_close( $curl );

echo $values[ 'token_type' ] . ' ' . $values[ 'access_token' ] . '<br />';

$curl = curl_init();

$ini_options[ CURLOPT_COOKIEJAR ] = '';
$ini_options[ CURLOPT_COOKIEFILE ] = '';
curl_setopt_array( $curl, $ini_options );

curl_setopt( $curl, CURLOPT_URL,
        'https://docs.google.com/feeds/documents/private/full' );
curl_setopt( $curl, CURLOPT_HTTPHEADER,
        array( 'GData-Version: 2.0', 'Authorization: ' . $values[ 'token_type' ] . ' ' . $values[ 'access_token' ] ) );
curl_setopt( $curl, CURLOPT_HEADER, true );
curl_setopt( $curl, CURLINFO_HEADER_OUT, true );


//sleep(((int)$expires_in)+120);

echo curl_exec( $curl );
$info = curl_getinfo( $curl );
var_dump( $info );
?>